<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <h1 style="text-align: center;">文档修改页面</h1>
            </div>
            <el-form ref="documentRef" :model="form" :rules="rules" label-position="top" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="所属档案" prop="archiveId">
                            <el-select v-model="form.archiveId" placeholder="请选择档案" @change="getArchiveById"
                                style="width: 100%;">
                                <el-option v-for="archive in archiveList" :key="archive.id" :label="archive.name"
                                    :value="archive.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="文件名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入文件名称" />
                        </el-form-item>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="文件类型" prop="fileType">
                                    <el-select v-model="form.fileType" placeholder="请选择文件类型">
                                        <el-option v-for="dict in iams_media_type" :key="dict.value" :label="dict.label"
                                            :value="dict.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="文件大小(Kb)" prop="fileSize">
                                    <el-input v-model="form.fileSize" placeholder="请输入文件大小(Kb)" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-form-item label="文件路径" prop="filePath">
                            <el-input v-model="form.filePath" placeholder="请输入文件路径" />
                        </el-form-item>
                        <el-form-item label="挂载目录" prop="directory">
                            <el-tree-select v-model="form.directory" :data="directory" check-strictly
                                :render-after-expand="false" style="width: 100%" @change="changeDirectory" />
                        </el-form-item>
                        <el-form-item label="存放位置" prop="fileLocation">
                            <el-input v-model="form.fileLocation" placeholder="请输入存放位置" />
                        </el-form-item>
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item label="真实性" prop="authenticity" label-position="left">
                                    <el-switch v-model="formBoolean.authenticity" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="完整性" prop="integrity">
                                    <el-switch v-model="formBoolean.integrity" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="可用性" prop="availability">
                                    <el-switch v-model="formBoolean.availability" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="安全性" prop="security">
                                    <el-switch v-model="formBoolean.security" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="文件内容">
                            <div class="editor-container">
                                <editor v-model="form.content"/>
                            </div>
                        </el-form-item>

                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入备注内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </template>
        </el-card>
    </div>
</template>

<script setup lang="js">
import { ref, computed, reactive, toRefs } from "vue";
import { useRoute } from "vue-router";
import { getDocument, updateDocument } from "@/api/manage/document";
import { getArchive, deleteDirectoryFiles, addDirectoryFiles, listArchive } from "@/api/manage/archive";

const { proxy } = getCurrentInstance();
const { iams_media_type } = proxy.useDict('iams_media_type');

const route = useRoute();

const data = reactive({
    form: {},
    rules: {
        name: [
            { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
    }
});

const archive = ref({});
const directory = ref([]);
const oldData = ref({});
const archiveList = ref([]);

const { form, rules } = toRefs(data);

// 定义需要转换的字段列表
const booleanFields = ['authenticity', 'integrity', 'availability', 'security'];

// 创建中间计算属性对象
const formBoolean = reactive({});
booleanFields.forEach(field => {
    formBoolean[field] = computed({
        get: () => form.value[field] === 1,
        set: (val) => { form.value[field] = val ? 1 : 0; }
    });
});

// 取消按钮
function cancel() {
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        archiveId: null,
        xuhao: null,
        name: null,
        fileType: null,
        fileSize: null,
        filePath: null,
        fileLocation: null,
        content: null,
        authenticity: null,
        integrity: null,
        availability: null,
        security: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        directory: null
    };
    proxy.resetForm("documentRef");
}

function changeDirectory(value) {
    console.log('Directory changed to:', value);
    form.value.directory = value;
}

/** 搜索档案 */
function getArchiveById() {
    getArchive(form.value.archiveId).then(response => {
        // console.log('API Response:', response.data); // 添加日志输出
        if (response.code == 200 && response.data) {
            // 确保 response.data.directory 是一个数组
            let directoryData = [];
            if (typeof response.data.directory === 'string') {
                try {
                    directoryData = JSON.parse(response.data.directory);
                } catch (e) {
                    console.error('Failed to parse JSON:', e);
                    proxy.$modal.msgError("解析目录数据失败");
                    return;
                }
            } else if (Array.isArray(response.data.directory)) {
                directoryData = response.data.directory;
            }

            // console.log('directoryData:', directoryData); // 添加日志输出

            directory.value = directoryData.map(item => ({
                value: item.id,
                label: item.label,
                children: item.children ? item.children.map(child => ({
                    value: child.id,
                    label: child.label
                })) : []
            }));

            // console.log('directory.value:', directory.value); // 添加日志输出

            archive.value = response.data;
        } else {
            proxy.$modal.msgError("档案不存在");
        }
    }).catch(error => {
        console.error('API Error:', error); // 添加日志输出
        proxy.$modal.msgError("查询档案失败：" + error.message);
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["documentRef"].validate(valid => {
        if (valid) {
            if (form.value.archiveId != oldData.value.archiveId || form.value.directory != oldData.value.directory) {
                console.log('Directory changed, updating...');
                deleteDirectoryFiles(oldData.value).then(res => {
                    addDirectoryFiles(form.value).then(response => {                 
                        console.log('Directory updated successfully:', form.value);
                    }).catch(error => {
                        console.error('Error updating directory:', error);
                    });
                });
            }
            updateDocument(form.value).then(response => {
                proxy.$modal.msgSuccess("修改成功");
                proxy.$router.push({ path: "/manage/document/doc-list" });
            });
        }
    });
}

onMounted(() => {
    reset();

    listArchive().then(response => {
        archiveList.value = response.rows;
    });

    const _id = route.query.id;
    getDocument(_id).then(response => {
        form.value = response.data;
        oldData.value = JSON.parse(JSON.stringify(response.data));
        getArchive(response.data.archiveId).then(response => {
            // console.log('API Response:', response.data); // 添加日志输出
            if (response.code == 200 && response.data) {
                // 确保 response.data.directory 是一个数组
                let directoryData = [];
                if (typeof response.data.directory === 'string') {
                    try {
                        directoryData = JSON.parse(response.data.directory);
                    } catch (e) {
                        console.error('Failed to parse JSON:', e);
                        proxy.$modal.msgError("解析目录数据失败");
                        return;
                    }
                } else if (Array.isArray(response.data.directory)) {
                    directoryData = response.data.directory;
                }

                // console.log('directoryData:', directoryData); // 添加日志输出

                directory.value = directoryData.map(item => ({
                    value: item.id,
                    label: item.label,
                    children: item.children ? item.children.map(child => ({
                        value: child.id,
                        label: child.label
                    })) : []
                }));

                // console.log('directory.value:', directory.value); // 添加日志输出

                archive.value = response.data;
            }
        })
    });
});
</script>

<style scoped>
/* 设置编辑器容器高度并允许滚动 */
.editor-container {
  /* 固定高度 */
  height: 400px; /* 或使用 max-height: 400px; */
  
  /* 超出内容显示滚动条 */
  overflow-y: auto;
  
  /* 可选样式 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px;
}

/* 如果编辑器内部有内容容器（如 .ql-editor），可能需要额外设置 */
.editor-container :deep(.ql-editor) {
  height: 100%;
  overflow-y: hidden; /* 防止内部产生双滚动条 */
}
</style>